<template>
  <div class="user-page page-main">
    <a-tabs v-model:activeKey="searchParams.loginType" @tab-click="changeTab">
      <a-tab-pane v-for="item in USERTYPE_OPTION" :key="item.value" :tab="item.label" />
    </a-tabs>
    <search-form :model="searchParams" @search="search">
      <a-form-item label="用户搜索：">
        <a-input v-model:value="searchParams.keywords" placeholder="请输入姓名或手机号" clearable />
      </a-form-item>

      <template v-if="collapse">
        <a-form-item label="用户等级：">
          <a-select v-model:value="levelData" placeholder="请选择" clearable filterable multiple>
            <a-select-option v-for="(item, index) in levelList" :key="index" :value="item.id">
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="用户分组：">
          <a-select v-model:value="groupData" placeholder="请选择" clearable filterable multiple>
            <a-select-option v-for="(item, index) in groupList" :key="index" :value="item.id">
              {{ item.groupName }}
            </a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="用户标签：">
          <a-select v-model:value="labelData" placeholder="请选择" clearable filterable multiple>
            <a-select-option v-for="(item, index) in labelList" :key="index" :value="item.id">
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="国家：">
          <a-select v-model:value="searchParams.country" placeholder="请选择" clearable @on-change="changeCountry">
            <a-select-option value="">全部</a-select-option>
            <a-select-option value="CN">中国</a-select-option>
            <a-select-option value="OTHER">国外</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="省份：">
          <a-cascader v-model:value="address" :options="addresData"
            :field-names="{ label: 'name', value: 'code', children: 'items' }" filterable clearable
            @change="handleChange" />
        </a-form-item>

        <a-form-item label="消费情况：">
          <a-select v-model:value="searchParams.payCount" placeholder="请选择" clearable>
            <a-select-option v-for="(item, index) in PAY_COUNT" :key="index" :value="item.value">
              {{ item.label }}
            </a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="时间选择：" class="timeBox">
          <a-range-picker v-model:value="timeVal" value-format="YYYY-MM-DD" />
        </a-form-item>

        <!--
                  
                 -->

        <a-form-item label="访问情况：">
          <a-select v-model:value="searchParams.accessType" placeholder="请选择" clearable>
            <a-select-option :value="0">全部</a-select-option>
            <a-select-option :value="1">首次访问</a-select-option>
            <a-select-option :value="2">时间段访问过</a-select-option>
            <a-select-option :value="3">时间段未访问</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="性别：">
          <a-radio-group v-model:value="searchParams.sex" button-style="solid">
            <a-radio-button value=""> 全部 </a-radio-button>
            <a-radio-button value="0"> 未知 </a-radio-button>
            <a-radio-button value="1"> 男 </a-radio-button>
            <a-radio-button value="2"> 女 </a-radio-button>
            <a-radio-button value="3"> 保密 </a-radio-button>
          </a-radio-group>
        </a-form-item>

        <a-form-item label="身份：">
          <a-radio-group v-model:value="searchParams.isPromoter" button-style="solid">
            <a-radio-button value=""> 全部 </a-radio-button>
            <a-radio-button value="1"> 推广员 </a-radio-button>
            <a-radio-button value="0"> 普通用户 </a-radio-button>
          </a-radio-group>
        </a-form-item>

        <!--
                  
                 -->
      </template>

      <a-form-item>
        <a class="ivu-ml-8" @click="collapse = !collapse">
          <template v-if="!collapse"> 展开
            <DownOutlined />
          </template>
          <template v-else> 收起
            <UpOutlined />
          </template>
        </a>
      </a-form-item>
    </search-form>
    <div class="table-toolbar">
      <a-button type="primary" @click="onSend">
        发送优惠券
      </a-button>
      <a-button type="primary" @click="setBatch('group')">
        批量设置分组
      </a-button>
      <a-button type="primary" @click="setBatch('label')">
        批量设置标签
      </a-button>
    </div>
    <g-table ref="tableRef" rowKey="uid"
      :rowSelection="{ selectedRowKeys: selectId, onChange: (selectedRowKeys, selectedRows) => onSelectChange(selectedRows) }"
      :columns="columns" :api="userList" :isExtra="true" :params="searchParams">
      <template #expandedRow="{ record }">
        <a-form label-position="left" layout="inline" class="demo-table-expand">
          <a-form-item label="身份：">
            <span>{{ record.isPromoter }}</span>
          </a-form-item>
          <a-form-item label="首次访问：">
            <span>{{ record.createTime }}</span>
          </a-form-item>
          <a-form-item label="近次访问：">
            <span>{{ record.lastLoginTime }}</span>
          </a-form-item>
          <a-form-item label="手机号：">
            <span>{{ record.phone }}</span>
          </a-form-item>
          <a-form-item label="标签：">
            <span>{{ record.tagName }}</span>
          </a-form-item>
          <a-form-item label="地址：">
            <span>{{ record.addres }}</span>
          </a-form-item>
          <a-form-item label="备注：" style="width: 100%; display: flex; margin-right: 10px">
            <span>{{ record.mark }}</span>
          </a-form-item>
        </a-form>
      </template>
    </g-table>

    <userDetail v-model:visible="visible" :data="activeRow" @change="search(false)" />
    <userExtension v-model:visible="isUp" :data="activeRow" @change="search(false)" />
    <userSet v-model:visible="isSet" :data="activeRow" :type="settype" :groupList="groupList" :labelList="labelList"
      @change="search(false)" />
    <userLvel v-model:visible="islevel" :data="activeRow" :levelList="levelList" @change="search(false)" />

    <userScore v-model:visible="isScore" :data="activeRow" @change="search(false)" />
    <a-modal v-model:visible="isSend" :width="900" title="优惠券" @ok="submit">
      <couponList handle="send" :userIds="selectId.join(',')" :keyNum="keyNum + 1" />
    </a-modal>
  </div>
</template>

<script setup lang="tsx">
import {
  spreadClearApi,
  userList,
  usergroupList,
  userlevelList,
  usertagList,
} from "./api";
import type { Iuser } from "./entity";
import userDetail from "./detail.vue";
import userExtension from "./userExtension.vue";
import userSet from "./userSet.vue";
import userScore from "./userScore.vue";
import userLvel from "./userLvel.vue";
import { USERTYPE_OPTION, PAY_COUNT } from "@/utils/constant";
import type { ILevel } from "@/types/user";
import type { Iusertag } from "./label/entity";
import type { Iusergroup } from "./group/entity";
import { cityListTree } from "../logistics/cityList/api";
import { Modal } from "ant-design-vue";
const searchParams = reactive({
  loginType: "",
  keywords: "",
  labelId: "",
  userType: "",
  sex: "",
  isPromoter: "",
  country: "",
  payCount: "",
  accessType: 0,
  dateLimit: "",
  province: "",
  city: "",
});
function changeTab() {
  search(false);
}
let visible = $ref(false);
let collapse = $ref(false);
let isUp = $ref(false);
let isSet = $ref(false);
let isScore = $ref(false);
let islevel = $ref(false)
let levelData = $ref([]);

let groupData = $ref([]);
let selectId = $ref([])
let labelData = $ref([]);
let timeVal = $ref<string[]>(["", ""]);
let levelList = $ref<ILevel[]>([]);
let labelList = $ref<Iusertag[]>([]);
let groupList = $ref<Iusergroup[]>([]);
let addresData = $ref([]);
let address = $ref([]);
let isSend = $ref(false)
let keyNum = $ref(0)
onMounted(() => {
  queryLevels();
  querygroups();
  querylabels();
  getCityList();
});
async function queryLevels() {
  let { list } = await userlevelList({ page: 1, limit: 100 });
  levelList = list;
}
async function querylabels() {
  let { list } = await usertagList({ page: 1, limit: 100 });
  labelList = list;
}
async function querygroups() {
  let { list } = await usergroupList({ page: 1, limit: 100 });
  groupList = list;
}
async function getCityList() {
  let res = await cityListTree();
  addresData = res;
}
function handleChange(value: string[]) {
  searchParams.province = value[0];
  searchParams.city = value[1];
}
function changeCountry() {
  if (searchParams.country === "OTHER" || !searchParams.country) {
    searchParams.province = "";
    searchParams.city = "";
    address = [];
  }
}
addresData;
const { tableRef, columns, search } = useTable<Iuser>([
  { title: "ID", dataIndex: "uid" },
  {
    title: "头像",
    dataIndex: "avatar",

    customRender: ({ record }) =>
      record.avatar ? <img class="img-thumbnail" src={record.avatar} /> : "",
  },
  { title: "姓名", dataIndex: "nickname" },
  { title: "用户等级", dataIndex: "level" },
  { title: "分组", dataIndex: "groupName" },
  { title: "推荐人", dataIndex: "spreadNickname" },
  { title: "手机号码", dataIndex: "phone" },
  { title: "余额", dataIndex: "nowMoney" },
  { title: "积分", dataIndex: "integral" },

  {
    title: "操作",
    dataIndex: "op",
    customRender: ({ record }) => (
      <>
        <table-button onClick={() => onDetails(record)}>账户详情</table-button>
        <table-button onClick={() => editPoint(record)}>积分余额</table-button>
        <table-button onClick={() => setBatch('group', record)}>设置分组</table-button>
        <table-button onClick={() => setBatch('label', record)}>设置标签</table-button>
        <table-button onClick={() => setPhone(record)}>修改手机号</table-button>
        <table-button onClick={() => onLevel(record)}>
          修改用户等级
        </table-button>
        <table-button onClick={() => setExtension(record)}>
          修改上级推广人
        </table-button>
        <table-button onClick={() => clearSpread(record)}>
          清除上级推广人
        </table-button>
      </>
    ),
  },
]);
let settype = $ref('')
function editPoint(data: Iuser) {
  activeRow = { ...data };
  isScore = true;
}
function setBatch(type: string, data?: Iuser) {
  activeRow = { ...data };
  if (data) {
    data.groupId = type == 'group' ? data.groupId : data.tagId
    activeRow = { ...data };
  }
  isSet = true;
  settype = type
}
const onSelectChange = (rows: any[]) => {
  console.log(rows);

  selectId = rows.map((e: any) => e.uid)
};
function onSend() {
  if (selectId.length === 0) return AntMessage.warning('请选择要设置的用户');
  isSend = true
}
function submit() {

}
function setPhone(data: Iuser) { }
function onLevel(data: Iuser) {
  activeRow = { ...data };
  islevel = true;
}
function setExtension(data: Iuser) {
  activeRow = { ...data };
  isUp = true;
}
function clearSpread(data: Iuser) {

  Modal.confirm({
    title: "提示",
    content: "是否解除上级推广人",
    onOk() {
      clearUp(data);
    },
  });
}
async function clearUp(data: Iuser) {
  spreadClearApi(data.uid).then(() => {
    AntMessage.success("修改成功");
    search(false);
  })
}
let activeRow = $ref<Partial<Iuser>>({});
function onDetails(data: Partial<Iuser> = {}) {
  activeRow = { ...data };
  visible = true;
}
</script>

<style lang="scss"></style>
